import { createRouter, createWebHistory } from "vue-router";
import jwtDecode from 'jwt-decode' // 确保正确导入
import component from "element-plus/es/components/tree-select/src/tree-select-option.mjs";

// 定义路由关系
const routes = [
  {
    path: '/',
    component: () => import('@/components/IndexLayout.vue'),
    children: [
      {
        path: '',             // /  -> 首页
        redirect: 'index'
      },
      {
        path: 'index',        // /index
        component : () => import('@/views/index.vue')
      },
      {
        path: 'promotions/:typeId',
        name: 'PromotionList',
        component : () => import('@/views/Promotion/promotionList.vue')
      },
      {
        path: 'search',       // /search?q'@.
        name: 'ProductResult',
        component: () => import('@/views/ProductResult.vue')
      },
      {
        path: 'promotions/groupbuy/:promotionId',
        name: 'GroupbuyActivityDetail',
        component: () => import('@/views/groupbuy/GroupbuyDetail.vue')
      },
      {
        path: '/group/:groupId',
        name: 'GroupDetail',
        component: () => import('@/views/groupbuy/GroupDetail.vue')
      },
      {
        path: '/promotions/seckill/:promotionId',
        name: 'SeckillDetail',
        component: () => import('@/views/promotion/seckill/SeckillDetail.vue')
      },
      {
        path: '/promotions/combo/:promotionId',
        name: 'ComboDetail',
        component: () => import('@/views/promotion/combodetail/ComboDetail.vue')
      },
      {
        path: '/promotions/fullReduction/:promotionId',
        name: 'FullReductionDetail',
        component: () => import('@/views/promotion/fullreduction/FullReductionDetail.vue')
      }
      // {
      //   path: '/invite/:inviteCode',
      //   name: 'GroupInvite',
      //   component: () => import('@/views/groupbuy/GroupInvite.vue')
      // }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { public: true } // 标记为公共路由，无需登录
  },
  {
    path: '/adminlogin',
    name: 'AdminLogin',
    component: () => import('@/views/admin/AdminLogin.vue'),
    meta: { public: true } // 标记为公共路由，无需登录
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/register.vue'),
    meta: { public: true } // 标记为公共路由，无需登录
  },
  {
    path: '/Dashboard',
    component : () => import('@/components/UserLayout.vue'),
    meta: { requiresAuth: true, role: 'user' }, // 需要登录，且角色为买家
    children: [
      {
        path: 'user/userInfo',
        component: () => import('@/views/user/UserInfo.vue')
      },
      {
        path: 'user/resetPassword',
        component: () => import('@/views/user/ResetPassword.vue')
      },
      {
        path: 'user/cart',
        component: () => import('@/views/user/MyCart.vue')
      },
      {
        path: 'user/orders',
        component: () => import('@/views/user/MyOrder.vue')
      },
      {
        path: 'user/wallet',
        component: () => import('@/views/user/MyWallet.vue')
      },
      {
        path: 'user/delivery',
        component: () => import('@/views/user/Delivery.vue')
      },
      {
        path: 'membership',
        component: () => import('@/views/user/MemberShip.vue')
      },
      {
        path: 'points-mall',
        component: () => import('@/views/user/PointsMall.vue'),
        meta: { title: '积分商城' }
      }
    ]
  },
  {
    path: '/merchant',
    component: () => import('@/components/MerchantLayout.vue'),
    redirect: '/merchant/info',
    meta: { requiresAuth: true, role: 'merchant' }, // 需要登录，且角色为商家
    children: [
      {
        path: 'info',
        component: () => import('@/views/merchant/MerchantInfo.vue')
      },
      {
        path: 'orders',
        component: () => import('@/views/merchant/MerchantOrders.vue')
      },
      {
        path: 'products',
        component: () => import('@/views/merchant/ProductManage.vue')
      },
      {
        path: 'promotions',
        component: () => import('@/views/merchant/PromotionManage.vue')
      },
      {
        path: 'refunds',
        component: () => import('@/views/merchant/RefundManage.vue')
      },
      {
        path: 'evaluations',
        component: () => import('@/views/merchant/EvaluationManage.vue')
      }
    ]
  },
  {
    path: '/admin',
    component: () => import('@/components/AdminLayout.vue'),
    meta: { requiresAuth: true, role: 'admin' },
    children: [
      { path: 'promotionCon', component: () => import('@/views/admin/Promotion.vue')  },
      { path: 'dashboard', component: () => import('@/views/admin/Dashboard.vue') },
      { path: 'spu', component: () => import('@/views/admin/SpuAudit.vue') },
      { path: 'merchant', component: () => import('@/views/admin/MerchantPendingList.vue') },
      { path: 'merchant-audit', component: () => import('@/views/admin/MerchantAudit.vue') },
      { path: 'comment', component: () => import('@/views/admin/CommentAudit.vue') },
      { path: 'user', component: () => import('@/views/admin/UserList.vue') },
      { path: 'notice', component: () => import('@/views/admin/NoticeManage.vue') },
      { path: 'category', component: () => import('@/views/admin/CategoryManage.vue') },
      { path: 'promotion', component: () => import('@/views/admin/Activity.vue') }
    ]
  },

  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('@/views/ProductDetail.vue'),
    props: true
  },
  {
  path: '/pay/choose',
  name: 'PayChoose',
  component: () => import('@/views/pay/PayChoose.vue')
  }
  
]

// 创建路由器
const router = createRouter({
  history: createWebHistory(),
  routes: routes
})

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  console.log(token)

  // 公共路由直接放行
  if (to.meta.public) {
    return next()
  }

  // 需要登录的路由
  if (to.meta.requiresAuth) {
    if (!token) {
      return next({ 
        name: 'Login', 
        query: { redirect: to.fullPath }
      })
    }

    // 验证 token
    try {
      // const response = await axios.get('/api/validateToken', {
      //   headers: { Authorization: `Bearer ${token}` }
      // })
      // if (response.data.code !== 200) {
      //   localStorage.removeItem('token')
      //   localStorage.removeItem('userInfo')
      //   return next({ name: 'Login', query: { redirect: to.fullPath } })
      // }

      // 从 token 中解析权限
      let decodedToken
      try {
        decodedToken = jwtDecode(token)
        // console.log('解析后的 token:', decodedToken)
      } catch (error) {
        console.error('token 解析失败:', error)
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        return next({ name: 'Login', query: { redirect: to.fullPath } })
      }

      const userRole = JSON.parse(decodedToken.sub).identity

      console.log(userRole)

      // 检查角色权限
      if (to.meta.role && userRole !== to.meta.role) {
        if (userRole === 'admin') {
          return next('/admin')
        } else if (userRole === 'merchant') {
          return next('/merchant')
        } else {
          return next('/Dashboard')
        }
      }
      return next()
    } catch (error) {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      return next({ name: 'Login', query: { redirect: to.fullPath } })
    }
  }

  // 根路径重定向
  // if (token) {
  //   try {
  //     const decodedToken = jwtDecode(token)
  //     const userRole = decodedToken.identity
  //     if (to.path === '/' || to.path === '/index') {
  //       if (userRole === 'admin') {
  //         return next('/admin/dashboard')
  //       } 
  //       else if (userRole === 'merchant') {
  //         return next('/merchant/info')
  //       } else {
  //         return next('/Dashboard/user/userInfo')
  //       }
  //     }
  //   } catch (error) {
  //     localStorage.removeItem('token')
  //     localStorage.removeItem('userInfo')
  //     return next({ name: 'Login', query: { redirect: to.fullPath } })
  //   }
  // }

  next()
})

export default router